<template>
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input clearable v-model="search.expertName" placeholder="专家姓名" style="width: 125px; margin-right: 15px">
        </el-input>
        <el-select clearable v-model="search.genderId" placeholder="性别">
          <el-option clearable :label="item.itemText" :value="item.itemValue" :key="item.itemValue"
            v-for="item in sexList" />
        </el-select>


        <el-select v-model="search.expertType" placeholder="专家类型" style="width: 125px; margin-right: 15px" clearable>
          <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue"
            v-for="item in expertTypeList" />
        </el-select>

        <el-select v-if="search.expertType == 1" clearable v-model="search.workUnitId" placeholder="所属单位">
          <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in unitNameList" />
        </el-select>

        <el-input v-if="search.expertType == 2" clearable v-model="search.workUnitName" placeholder="所属单位"
          style="width: 125px; margin-right: 15px">
        </el-input>

        <el-input clearable v-model="search.job" placeholder="职务" style="width: 125px; margin-right: 15px">
        </el-input>

        <el-select clearable v-model="search.expertiseAreaId" placeholder="擅长领域">
          <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue" v-for="item in areaList" />
        </el-select>

        <el-button class="ordinary" @click="getTableList">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right">
        <el-button type="primary" @click="submit()">上报中交</el-button>
        <el-button class="ordinary" @click="getExportBtn()" v-limit="'ZJHRC:ZJK:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="handleDetect()" v-limit="'ZJHRC:ZJK:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'ZJHRC:ZJK:ADD'">专家新增</el-button>
      </el-col>
    </el-row>
    <div>
      <Table :loading="isLoading" :tableArr="tableDate" :pagination="pagination" :columns="columns"
        :total="pagination.total" @delectTable="delectIds"
             @currentChange="(current) => {
               pagination.page = current;
               getTableList();
             }"
             @sizeChange="(size) => {
               pagination.limit = size;
               getTableList();
             }">
        <template #operate="{ row }">
          <div v-if="row.status == '待提交'">
            <el-button size="small" class="ordinary" @click="handleEdit(row)" v-limit="'ZJHRC:ZJK:EDIT'">编辑</el-button>
            <el-button size="small" class="ordinary" @click="handletj(row)" v-limit="'ZJHRC:ZJK:SUBMIT'">提交</el-button>
            <el-button size="small" class="ordinary" @click="handlexq(row)" >详情</el-button>
          </div>
          <div v-if="row.status == '办理中'">
            <el-button size="small" class="ordinary" @click="handlesh(row)" v-limit="'ZJHRC:ZJK:EXAMINE'">审核</el-button>
            <el-button size="small" class="ordinary" @click="handlexq(row)" >详情</el-button>
          </div>
           <div v-if="row.status == '正常办结'">
<!--            <el-button size="small" class="ordinary" @click="handlecx(row)">撤销</el-button>-->
             <el-button size="small" class="ordinary" @click="handlexq(row)" >详情</el-button>
             <el-button size="small" class="ordinary" @click="handlebg(row)" v-limit="'ZJHRC:ZJK:BG'" >变更</el-button>
             <el-button size="small" class="ordinary" @click="handlebg(row)"  >变更</el-button>
           </div>
          <div v-if="row.status == '已驳回'">
            <el-button size="small" class="ordinary" @click="handleEdit(row)" v-limit="'ZJHRC:ZJK:EDIT'">编辑</el-button>
            <el-button size="small" class="ordinary" @click="handletj(row)" v-limit="'ZJHRC:ZJK:SUBMIT'">提交</el-button>
            <el-button size="small" class="ordinary" @click="handlexq(row)" >详情</el-button>
          </div>
          <div>

          </div>
        </template>
      </Table>
    </div>
    <InfoDialog v-if="infoDialog" :dialogVisable="infoDialog" :id="id" :flag="flag" :isProcess="isProcess" :isExamine="isExamine" @changeDialog="changeDialog" :orgAllList="orgAllList"
    @dialogVisable="changeDialog"   @changeSuccess="changeSuccess" @changerRefuse="changerRefuse" :unitNameList="unitNameList"></InfoDialog>
    <InfoDialogxq :dialogVisablexq="infoDialogxq" :id="id" :flag="flag" @changeDialogxq="changeDialogxq"
      @changeSuccess="changeSuccess" @changerRefusexq="changerRefusexq" :unitNameList="unitNameList"></InfoDialogxq>
  </div>

  <el-dialog v-model="dealVisible" title="系统正在处理中....." width="40%" top="14%" height="400" :show-close="false"
    :close-on-click-modal="false">
    <el-alert type="success" :closable="false" style="margin-bottom:20px" description="当前流程正在处理中,请稍等……">
    </el-alert>
  </el-dialog>
</template>
<script>
import {
getConfirm,
getDelect,
  getbgById,
getDetailById,
getDictionary,
getExport,
getLock,
getTable,
getUnit,
getUnlock,
startProcess,
getApplicant
} from "@/views/expert/api/expertsManager";

import Table from "@/views/science/components/table/table.vue";
import { Modals, tips } from "@/views/science/components/tips/tips";
import { ElAlert } from 'element-plus';
import {nextTick, onMounted, reactive, ref, toRefs} from "vue";
import { useStore } from "vuex";
import InfoDialog from "./InfoDialog.vue";
import InfoDialogxq from "./InfoDialogxq.vue";
import tableHead from "./tableHeader.json";
import request from "@/utils/request";
import * as proxy from "@/constants/proxy";

export default {
  components: {
    Table,
    InfoDialog,
    InfoDialogxq,
    ElAlert
  },
  setup() {
    const store = useStore();

    // 发送请求
    onMounted(() => {
      // 获取数据字典
      getCodeList();
      // 获取单位
      getUnitList();
      // 列表信息table
      getTableList();
      // 获取单位信息
      getOrgList();
    });
    let data = reactive({
      status: 0, //0编辑，1审核
      dealVisible: false,
      times: null,
      id: "",
      flag: 1,
      isProcess:false,
      isExamine:false,
      infoDialog: false,
      ids: [],
      pagination: { page: 1, limit: 10, total: 0 }, //分页
      isLoading: false,

      sexList: [],
      areaList: [],
      unitNameList: [],
      awardList: [],
      tableDate: [],
      expertTypeList: [],
      columns: tableHead.softwareHeader,
      search: {
        type: "1",
        expertType: '',
        expertName: "",
        genderId: "",
        department: "",
        job: "",
        expertiseAreaId: "",
      },
      infoDialogxq: false,
    });

    //提交...
    let handletj = (row) => {

      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await startProcess({
            flowKey: 'experts',
            businessKey: row.id,
            businessType: 'YW04',
            random: (new Date()).valueOf()
          });
          if (res.data.code == 200) {
            data.dealVisible = true
            deal(row.id, 1)
          }else{
            tips(res.data.message, 'warning')
          }
        })
        .catch(() => { });
    }
    let deal = (id, state) => {
      data.times = setInterval(async () => {
        getDetailById(id).then((res) => {
          const resData = res.data.data
          if (resData.status == state) {
            data.dealVisible = false
            nextTick(() => {
              data.infoDialog = false
              data.infoDialogxq = false //详情
              getTableList()
              clearTimeout(data.times)
            })
          }
        })
      }, 1000);
    }

    // 解锁
    let getUnlockBtn = async () => {
      if (data.ids.length == 1) {
        Modals("是否解锁选择内容", "提示", "warning")
          .then(async () => {
            let res = await getUnlock(data.ids);
            if (res.data.success) {
              tips("解锁成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("解锁功能不可批量操作", "warning");
      }
    };
    //  锁定
    let getLockBtn = async () => {
      if (data.ids.length == 1) {
        Modals("是否锁定选择内容", "提示", "warning")
          .then(async () => {
            let res = await getLock(data.ids);
            if (res.data.success) {
              tips("锁定成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("锁定功能不可批量操作", "warning");
      }
    };

    // 导出功能的实现

    let getExportBtn = () => {
      let msg = '是否导出全部数据'
      if (data.ids.length > 0) {
        msg = '是否导出所选数据'
      }
      Modals(msg, "提示", "warning")
        .then(async () => {
          let obj = {
            ...data.search,
            ids: data.ids,
          }
          await getExport(obj, "专家库");
        })
        .catch(() => {
          console.log("点击了取消");
        });
    };
    // 确定当前流程
    let handleConfirm = async (row) => {
      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await getConfirm(row.id);
          if (res.data.success) {
            getTableList();
          }
        })
        .catch(() => { });
    };

    // 批量删除
    const handleDetect = async () => {
      if (data.ids.length) {
        Modals("是否删除选择内容", "提示", "warning").then(async () => {
          let list = []
          data.tableDate.forEach(e => {
            if (data.ids.includes(e.id)) {
              list.push(e.status)
            }
          })
          if (list.includes('办理中') || list.includes('正常办结') || list.includes('已退回') || list.includes('已撤办') || list.includes('强制办结') || list.includes('已废弃') || list.includes('已挂起')) {
            tips('只允许删除待提交和已驳回状态的数据', 'warning')
          } else {
            let res = await getDelect(data.ids);
            if (res.data.success) {
              tips("删除成功", "success");
              getTableList();
            }
          }
        })
          .catch(() => {
            console.log("点击了取消");
          });
      } else {
        tips("请选择", "warning");
      }
    };
    const handlebg = async (row) => {
      Modals("是否变更选择内容", "提示", "warning").then(async () => {


        let res = await getbgById(row.id);
        if (res.data.success) {
          tips("变更成功", "success");
          getTableList();
        }

      }).catch(() => {
        console.log("点击了取消");
      });

    };
    let loading = ref(true)
    // 获取列表信息
    let getTableList = () => {

      data.isLoading = true,

        getTable({
          current: data.pagination.page,
          size: data.pagination.limit,
          ...data.search,
        }).then((res) => {


          let resData = res.data.data // 获取列表数据
          resData.records.map((item) => {
            if (item.status == 0) {
              item.status = "待提交"
            } else if (item.status == 1) {
              item.status = "办理中"
            } else if (item.status == 2) {
              item.status = "正常办结"
            } else if (item.status == 3) {
              item.status = "已退回"
            }
            else if (item.status == 4) {
              item.status = "已撤办"
            }
            else if (item.status == 5) {
              item.status = "强制办结"
            }
            else if (item.status == 6) {
              item.status = "已废弃"
            }
            else if (item.status == 7) {
              item.status = "已挂起"
            }
            else if (item.status == 8) {
              item.status = "已驳回"
            }
            if (item.reportStatus == null) {
              item.reportStatus = "待上报中交"
            }else if (item.reportStatus == 2) {
              item.reportStatus = "已上报中交"
            }
          })
          data.tableDate = resData.records;
          data.pagination.total = res.data.data.total;
          data.isLoading = false;
        });
    };

    // 获取ids

    let delectIds = (ids) => {
      data.ids = ids;
    };

    // 单位
    let getUnitList = () => {
      getUnit({}).then((res) => {
        data.unitNameList = res.data.data;
      });
    };

    //  用户列表
    let getCodeList = () => {
      getDictionary(["ZJYRC_ZJLX", "SEX", 'ZJYRC_SCLY']).then((res) => {
        data.expertTypeList = res.data.data.ZJYRC_ZJLX;
        data.sexList = res.data.data.SEX;
        data.areaList = res.data.data.ZJYRC_SCLY;
      });
    };

    let changerRefuse = () => {

      data.dealVisible = true

      deal(data.id, 8)

    }
    let changerRefusexq = () => {

      data.dealVisible = true

      deal(data.id, 8)

    }

    let changeSuccess = () => {

      data.dealVisible = true


      data.times = setInterval(async () => {

        getDetailById(data.id).then((res) => {

          const resData = res.data.data

          if (resData.status == 2 || resData.status == 1 && resData.currTaskTd !== data.taskId) {

            data.dealVisible = false
            getTableList()
            nextTick(() => {

              data.infoDialog = false
              data.infoDialogxq = false//详情

              getTableList()

              clearTimeout(data.times)

            })

          }

        })
      }, 1000);

    }



    // 新增
    let handleAdd = () => {
      data.flag = 1;

      data.infoDialog = true;
    };
    // 编辑

    let handleEdit = (row) => {
      data.flag = 2;
      data.id = row.id;
      data.infoDialog = true;
    };

    // 审核按钮
    const handlesh = (row) => {
      data.taskId = row.currTaskTd
      data.flag = 3;
      data.isExamine = true
      data.isProcess=true
      data.id = row.id;
      data.infoDialog = true;
    }

    let handlexq = (row) => {
      console.log(row,row.status,'handlexqhandlexqhandlexq');
      if(row.status=="待提交"){
        data.isProcess=false
      }else{
        data.isProcess=true
      }
      data.flag = 3;
      data.id = row.id;
      data.isExamine = false
      data.infoDialog = true;
    };
    let changeDialog = (value) => {
      data.id = "";
      data.flag = 1;
      console.log(value,'changeDialog');
      // 分页刷新列表
      data.infoDialog = false;
      if (value) {
        data.pagination.page = 1;
        getTableList();
      }
    };

    let changeDialogxq = (value) => {
      data.id = "";
      data.flag = 1;

      if (value) {
        data.pagination.page = 1;
        getTableList();
      }

      data.infoDialogxq = false;
    };

    const submit = async () => {
      // tips("该功能正在开发中.....", "warning");

      if (data.ids.length == 1) {
        Modals("是否上报选择内容", "提示", "warning").then(async () => {
          let list = []
          let reportStatus = []
          data.tableDate.forEach(e => {
            if (data.ids.includes(e.id)) {
              list.push(e.status)
              reportStatus.push(e.reportStatus)
            }
          })
          if (list.includes('办理中') || list.includes('正常办结') || list.includes('已退回') || list.includes('已撤办') || list.includes('强制办结') || list.includes('已废弃') || list.includes('已挂起')) {
            tips('只允许上报待提交和已驳回状态的数据', 'warning')
          } else if (reportStatus.includes('已上报中交')) {
            tips('此数据已上报中交', 'warning')
          } else {
            let res = await getApplicant(data.ids);
            if (res.data.success) {
              tips("上报成功,等待审核", "success");
              getTableList();
            }
          }
        }).catch(() => {
              console.log("点击了取消");
        });
      } else {
        tips("请选择一条数据", "warning");
      }

    }
    const orgAllList = ref([]);
    const getOrgList = () =>{
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res =>{
        orgAllList.value = res.data.data
      })
    }
    return {
      ...toRefs(data),
      changeSuccess,
      submit,
      handlesh,
      store,
      handleEdit,
      handleAdd,
      changeDialog,
      getTableList,
      getLockBtn,
      getExportBtn,
      getUnlockBtn,
      delectIds,
      handleConfirm,
      handleDetect,
      handletj,
      changerRefuse,
      changerRefusexq,
      handlexq,
      changeDialogxq,
      handlebg,
      orgAllList,
    };
  },
};
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}
</style>
